//
//  MNDPersonalCenterViewController.m
//  minidai
//
//  Created by Vitas on 2018/5/31.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDPersonalCenterViewController.h"
#import "MNDManagerAccountViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MNDDepositBankCardViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDMyProfileViewController.h"
#import "NSString+ReplaceAsterisk.h"
#import "SYClearCache.h"
#import <UMPush/UMessage.h>
#import "MNDSafeSettingViewController.h"
#import "MNDAboutViewController.h"

@interface MNDPersonalCenterViewController ()

//头像
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
//用户名
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
//用户手机号
@property (weak, nonatomic) IBOutlet UILabel *userPhoneLabel;
// 风险评测状态
@property (weak, nonatomic) IBOutlet UILabel *riskAssessmentStatusLabel;
//缓存
@property (weak, nonatomic) IBOutlet UILabel *totalCacheSizeLabel;
//存管状态
@property (weak, nonatomic) IBOutlet UILabel *depositLabel;


/**
 是否开户
 */
@property (nonatomic, assign) BOOL isOpenAccount;
@end

@implementation MNDPersonalCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    self.totalCacheSizeLabel.text = [NSString stringWithFormat:@"%.02fM", [SYClearCache folderSizeAtPath]];
    [self initialBarbuttonItems];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    NSArray *leftBarButtonItems = self.navigationItem.leftBarButtonItems;
    for (UIBarButtonItem *item in leftBarButtonItems) {
        [item setTintColor:kColorBackButtonColor];
    }
    
    [self loadDepositInfo];
    [self loadUserInfos];
    
    if (self.isOpenAccount) {
        self.depositLabel.text = @"查看";
        self.depositLabel.textColor = kColor9;
    } else {
        self.depositLabel.text = @"去开通";
        self.depositLabel.textColor = kColorDarkOrange;
    }
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"账号管理"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(goAccountManagerAction:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)setupUI {
    self.iconImageView.layer.cornerRadius = self.iconImageView.bounds.size.height*0.5;
    self.iconImageView.clipsToBounds = YES;
    [self configUserInfo:self.user];
}

#pragma mark - Network

- (void)loadUserInfos {
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    [APIManager sendRequestWithPath:API_USER_BASE_INFO
                         parameters:[MNDSign signedParam]
                             method:kXMHTTPMethodGET
                          onSuccess:^(ResponseModel *responseModel) {
                              
                              if (responseModel.status == ResponseSuccess) {
                                  [NetworkProgressHUD hideHud];
                                  weakself.user = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
                                  NSLog(@"data: %@", responseModel.data);
                                  [weakself configUserInfo:weakself.user];
                              } else {
                                  NSDictionary *dict = responseModel.msg;
                                  if (dict && dict.count > 0) {
                                      [NetworkProgressHUD showHudMsg:dict[@"error"]];
                                  } else {
                                      [NetworkProgressHUD showHudMsg:@"获取数据失败"];
                                  }
                              }
                          } onFailure:^(NSError *error) {
                              [NetworkProgressHUD showHudNetworkError:error];
                          }];
}

- (void)configUserInfo:(MNDUserModel *)userModel {
    UIImage *avatarPlaceholder = [UIImage imageNamed:@"user_center_avatar_color"];
    if (userModel.userPhoto.length > 0) {
        [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:userModel.userPhoto] placeholderImage:avatarPlaceholder];
    } else {
        self.iconImageView.image = avatarPlaceholder;
    }
    
    self.userNameLabel.text = userModel.userName;
    self.userPhoneLabel.text = [userModel.userPhone replaceWithAsteriskAtRange:NSMakeRange(3, 4)];
    if (userModel.userRiskEvaluationState.integerValue == -1) {
        self.riskAssessmentStatusLabel.text = @"未测评";
        self.riskAssessmentStatusLabel.textColor = kColorDarkOrange;
    } else {
        self.riskAssessmentStatusLabel.text = userModel.userRiskEvaluationType;
        self.riskAssessmentStatusLabel.textColor = kColor9;
    }
}

- (void)loadDepositInfo {
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_GET_DEPOSIT_INFO parameters:[MNDSign signedParamWithDict:@{@"perfect_type": @"2"}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseFailure) {
            NSString *sign = responseModel.msg[@"sign"];
            if ([sign isEqualToString:kOpenAccount]) {
                weakself.depositLabel.text = @"去开通";
                weakself.depositLabel.textColor = kColorDarkOrange;
                weakself.isOpenAccount = NO;
            } else {
                weakself.depositLabel.text = @"查看";
                weakself.depositLabel.textColor = kColor9;
                weakself.isOpenAccount = YES;
            }
        } else {
            weakself.depositLabel.text = @"查看";
            weakself.depositLabel.textColor = kColor9;
            weakself.isOpenAccount = YES;
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

//账号管理
- (void)goAccountManagerAction:(id)sender{
    
    MNDManagerAccountViewController *accountVC = [UIStoryboard viewControllerWithIdentifier:@"MNDManagerAccountViewController"];
    accountVC.user = self.user;
    [self.navigationController pushViewController:accountVC animated:YES];
    
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
        MNDMyProfileViewController *profileVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDMyProfileViewController"];
        profileVC.user = self.user;
        [self.navigationController pushViewController:profileVC animated:YES];
    }
    
    if (indexPath.section == 1) {
        //存管
        if (indexPath.row == 0) {
            if (!self.isOpenAccount) {
                [self toOpenDepository];
            } else {
                MNDDepositBankCardViewController *bankCardVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositBankCardViewController description]];
                [self.navigationController pushViewController:bankCardVC animated:YES];
            }
        }else if (indexPath.row == 1) {
            MNDSafeSettingViewController *safeResetVC = [UIStoryboard viewControllerWithIdentifier:@"MNDSafeSettingViewController"];
            [self.navigationController pushViewController:safeResetVC animated:YES];
        }else {
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
            MNDAboutViewController *aboutVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDAboutViewController"];
            [self.navigationController pushViewController:aboutVC animated:YES];
        }
    }
    //缓存
    if (indexPath.section == 2 && indexPath.row == 0) {
        
        WeakSelf(self);
        [SYClearCache cleanCache:^{
            [NetworkProgressHUD showHudMsg:@"清理成功"];
            
            weakself.totalCacheSizeLabel.text = [NSString stringWithFormat:@"%.02fM", [SYClearCache folderSizeAtPath]];
        }];
    }
}

- (void)toOpenDepository {
    
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
    MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
    realVC.fromNaviIndex = index;
    
    [self.navigationController pushViewController:realVC animated:YES];
}

//登出
- (IBAction)logoutAction:(id)sender {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_USER_LOGOUT parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            [weakself clearUserContents];
            
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"退出失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)clearUserContents {
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    //删除消息推送设置的别名
    [UMessage removeAlias: user.user_code type:@"minidai" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"删除别名失败: %@", error);
        } else {
            NSLog(@"删除别名成功: %@", responseObject);
        }
    }];
    //清除用户数据
    
    [MNDLoginUserModel deleteAllUserDatas];
    [UserDefaultsTool removeForKey:kOpenDepositAlert];
    //清空手势密码
    [UserDefaultsTool removeForKey:kGesturePassword];
    //清空手势错误次数
    [UserDefaultsTool removeForKey:kErrorCount];
    //关闭手势密码
    [UserDefaultsTool removeForKey:kFingerPassword];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"clearPomeCircleData" object:nil];
    [APIManager setGeneralHeaderValue:nil forField:@"USERCODE"];
    
    [self clearWebViewCookies];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)clearWebViewCookies {
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    //缓存web清除
    //    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
